package io.dcloud.uniplugin;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;

import java.util.HashMap;

import io.dcloud.feature.uniapp.UniSDKInstance;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.ui.action.AbsComponentData;
import io.dcloud.feature.uniapp.ui.component.AbsVContainer;
import io.dcloud.feature.uniapp.ui.component.UniComponent;
import io.dcloud.feature.uniapp.ui.component.UniComponentProp;

import static com.taobao.weex.WXEnvironment.getApplication;

public class TestWebView extends UniComponent<WebView> {
    private WebView webView;
    //持有组建的当前weex实例
    private UniSDKInstance instance;
    //要加载的HTML文件，此文件放在assets下的html文件夹下
    private String url="";
    //浏览器加载界面是否完成
    private boolean  mLoadFinish=false;

    public TestWebView(UniSDKInstance instance, AbsVContainer parent, AbsComponentData basicComponentData) {
        super(instance, parent, basicComponentData);
    }
    //初始化webView设置一些参数
    @SuppressLint("SetJavaScriptEnabled")
    private void init(){
//        webView.setInitialScale(100);
//        webView.addJavascriptInterface(this,"native");
        WebSettings webSettings=webView.getSettings();
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setAllowFileAccess(false); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);// 实现8倍缓存
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        String appCachePath = getApplication().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setDatabaseEnabled(true);

        Log.d("webView","webView");
       // 复写shouldOverrideUrlLoading()方法，使得打开网页时不调用系统浏览器， 而是在本WebView中显示
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d("webView",url);
//                view.loadUrl(url);
                return false;
            }
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onPageFinished(WebView view, String url) {
                mLoadFinish=true;
                //这里出发webView组件的finish事件，表示网页已经加载完成
                fireEvent("finish");
            }
        });
    }
    @UniJSMethod
    public void closeWebView() {
        this.webView.resumeTimers();
        this.webView.destroy();
    }
    @Override
    protected WebView initComponentHostView(Context context) {
        //新建webView
        this.webView = new WebView(context);
        init();
        return this.webView;
    }
    @UniComponentProp(name = "path")
    public void setPath(String path) {
      this.url=path;
      this.webView.loadUrl(this.url);
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onFinishLayout() {
        super.onFinishLayout();
    }
    //为html提供的通用的触发webView在weex中的对应方法名的事件
    @JavascriptInterface
    public void fireWeexEvent(final String weexMethod, String param){
        String data="";
        if(param!=null){
            data=param;
        }
        final HashMap map=new HashMap();
        map.put("data",data);
        this.webView.post(new Runnable() {
            @Override
            public void run() {
                fireEvent(weexMethod,map);
            }
        });
    }
    /*为weex界面提供的调用h5中js方法的接口*/
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @JSMethod
    public void executeJsFunction(String functionName, String param, final JSCallback callback){
        if (!mLoadFinish){
            return;
        }
        if (!TextUtils.isEmpty(functionName)) {
            webView.evaluateJavascript("javascript:"+functionName+"("+param+")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                    if(callback!=null){
                        HashMap map=new HashMap();
                        map.put("res",value);
                        callback.invoke(map);
                    }
                }
            });
        }
    }
    @Override
    protected void onCreate() {
        super.onCreate();
    }
    @Override
    public void onActivityResume() {
        super.onActivityResume();
    }
    @Override
    public void onActivityPause() {
        super.onActivityPause();

    }

    @Override
    public void onActivityDestroy() {
        super.onActivityDestroy();
        this.webView.resumeTimers();
        this.webView.destroy();
    }
}
